<template>
  <div class="user-manage">
    <div class="page-header">
      <h2>用户管理</h2>
      <a-button type="primary" @click="showAddModal">
        <template #icon>
          <PlusOutlined />
        </template>
        新增用户
      </a-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="账号">
          <a-input v-model:value="searchForm.username" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-model:value="searchForm.nickname" placeholder="请输入昵称" />
        </a-form-item>
        <a-form-item label="角色">
          <a-select v-model:value="searchForm.role" placeholder="请选择角色" style="width: 120px">
            <a-select-option :value="undefined">全部</a-select-option>
            <a-select-option :value="0">管理员</a-select-option>
            <a-select-option :value="1">普通用户</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sex'">
          <a-tag :color="record.sex === 1 ? 'blue' : 'pink'">
            {{ record.sex === 1 ? '男' : '女' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'role'">
          <a-tag :color="record.role === 0 ? 'red' : 'green'">
            {{ record.role === 0 ? '管理员' : '普通用户' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="record.status === 1 ? 'success' : 'error'">
            {{ record.status === 1 ? '正常' : '停用' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="showEditModal(record)">编辑</a-button>
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(record.id)">
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form :model="formState" :rules="rules" ref="formRef" :label-col="{ span: 6 }">
        <a-form-item label="账号" name="username" v-if="!isEdit">
          <a-input v-model:value="formState.username" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item label="密码" name="password" v-if="!isEdit">
          <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="昵称" name="nickname">
          <a-input v-model:value="formState.nickname" placeholder="请输入昵称" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="性别" name="sex">
          <a-select v-model:value="formState.sex" placeholder="请选择性别">
            <a-select-option :value="0">女</a-select-option>
            <a-select-option :value="1">男</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select v-model:value="formState.role" placeholder="请选择角色">
            <a-select-option :value="0">管理员</a-select-option>
            <a-select-option :value="1">普通用户</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status" placeholder="请选择状态">
            <a-select-option :value="0">停用</a-select-option>
            <a-select-option :value="1">正常</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="formState.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { pageUser, addUser, updateUser, deleteUser } from '@/api/user'
import type { UserVO } from '@/types/api'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'

// 搜索表单
const searchForm = reactive({
  username: undefined,
  nickname: undefined,
  role: undefined,
})

// 表格列定义
const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 100 },
  { title: '账号', dataIndex: 'username', key: 'username' },
  { title: '昵称', dataIndex: 'nickname', key: 'nickname' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '性别', dataIndex: 'sex', key: 'sex', width: 80 },
  { title: '角色', dataIndex: 'role', key: 'role', width: 100 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80 },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    customRender: ({ text }: any) => dayjs(text).format('YYYY-MM-DD HH:mm'),
  },
  { title: '操作', key: 'action', width: 150 },
]

const dataSource = ref<UserVO[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
})

// 弹窗相关
const modalVisible = ref(false)
const modalTitle = ref('新增用户')
const isEdit = ref(false)
const formRef = ref()
const formState = reactive({
  id: undefined as string | undefined,
  username: '',
  password: '',
  nickname: '',
  email: '',
  sex: undefined as number | undefined,
  role: 1,
  status: 1,
  remark: '',
})

const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const res = await pageUser({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    })
    dataSource.value = res.data.list
    pagination.total = parseInt(res.data.total)
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置
const handleReset = () => {
  searchForm.username = undefined
  searchForm.nickname = undefined
  searchForm.role = undefined
  pagination.current = 1
  fetchUserList()
}

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchUserList()
}

// 显示新增弹窗
const showAddModal = () => {
  modalTitle.value = '新增用户'
  isEdit.value = false
  resetForm()
  modalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: UserVO) => {
  modalTitle.value = '编辑用户'
  isEdit.value = true
  Object.assign(formState, {
    id: record.id,
    nickname: record.nickname,
    email: record.email,
    sex: record.sex,
    role: record.role,
    status: record.status,
    remark: record.remark,
  })
  modalVisible.value = true
}

// 弹窗确定
const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    if (isEdit.value) {
      await updateUser(formState as any)
      message.success('编辑成功')
    } else {
      await addUser(formState as any)
      message.success('新增成功')
    }
    modalVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 弹窗取消
const handleModalCancel = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  formState.id = undefined
  formState.username = ''
  formState.password = ''
  formState.nickname = ''
  formState.email = ''
  formState.sex = undefined
  formState.role = 1
  formState.status = 1
  formState.remark = ''
  formRef.value?.resetFields()
}

// 删除
const handleDelete = async (id: string) => {
  try {
    await deleteUser({ id })
    message.success('删除成功')
    fetchUserList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-manage {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #4a9eff;
  font-size: 24px;
}

.search-bar {
  margin-bottom: 24px;
  padding: 16px;
  background: rgba(26, 31, 58, 0.5);
  border-radius: 8px;
}
</style>

